package it.david.javassist

import java.util.jar.JarEntry
import java.util.jar.JarFile
import java.util.jar.JarOutputStream
import java.util.zip.ZipEntry

public class JarZipUtils{

    public static void unZipJar(String jarPath, String destDirPath){
        if (jarPath.endsWith('.jar')){
            JarFile jarFile = new JarFile(jarPath)
            Enumeration<JarEntry> jarentrys = jarFile.entries();
            while (jarentrys.hasMoreElements()){
                JarEntry jarEntry = jarentrys.nextElement()
                if (jarEntry.directory) {
                    continue
                }
                String entryName = jarEntry.getName()
                String outFileName = destDirPath + "/" + entryName
                File file = new File(outFileName)
                file.getParentFile().mkdir()
                InputStream inputStream = jarFile.getInputStream(jarEntry)
                FileOutputStream fileOutputStream = new FileOutputStream(outFileName)
                fileOutputStream << inputStream
                fileOutputStream.close()
                inputStream.close()
            }
            jarFile.close()
        }
    }

    public static void zipJar(String packagePath, String destPath){
        File file = new File(packagePath)
        JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(destPath))
        file.eachFileRecurse {File f ->
            String entryName = f.getAbsolutePath().substring(file.absolutePath.length() + 1)
            outputStream.putNextEntry(new ZipEntry(entryName))
            if (!f.directory){
                InputStream inputStream = new FileInputStream(f)
                outputStream << inputStream
                inputStream.close()
            }
        }
        outputStream.close()
    }
}